import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import an49 from '@mmstudio/an000049';
import { tbproject, tbpteam, tbteam } from '../../../../../atoms/db';

const logger = anylogger('pages/api/team/teamxq/content/s001.api');

export type Result = {
	ok: true;
	data: Pick<ITbteam, 'team_id' | 'teamname' | 'teammate'>[];
	mate: Pick<ITbpteam, 'name'>[];
	options: Pick<ITbpteam, 'originalclass' | 'originalmajor'>[]
} | {
	ok: false;
	message: string;
};

export type Message = void;

/**
 * pages/api/team/teamxq/content/s001.api
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const data = await tbteam().select('teamname', 'team_id', 'teammate');


		/**选择框数据并排序 */
		logger.debug('ssssssssssssssssss');
		const options = await tbpteam()
			// .distinct('grade')
			.distinct('originalclass')
			.distinct('originalmajor')
			.orderBy('originalclass', 'asc')
			.orderBy('originalmajor', 'asc');

		/** 关联表取数据*/

		const d1 = await tbteam().distinct('team_id');
		const d2 = d1.map((a) => {
			return a.team_id;
		});
		const mate = await tbpteam().select('name', 'team_id').whereIn('team_id', d2);


		res.status(200).json({
			ok: true,
			data,
			mate,
			options
		});

	} catch (error) {
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
